package com.cvte.testui;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.icu.lang.UCharacter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.cvte.testui.adapter.BtDevAdapter;
import com.cvte.vdt.uartservice.aidl.IVDTUartBluetoothAidl;
import com.cvte.vdt.uartservice.aidl.IVDTUartCallback;
import com.cvte.vdtlibrary.bluetooth.EntityBluetoothDevice;
import com.cvte.vdtlibrary.bluetooth.EnumBTRecModeStatus;
import com.cvte.vdtlibrary.bluetooth.EnumBTSendModeStatus;
import com.cvte.vdtlibrary.bluetooth.EnumBluetoothKey;
import com.cvte.vdtlibrary.bluetooth.EnumBluetoothMode;
import com.cvte.vdtlibrary.bluetooth.EnumBtDeviceStatus;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener,AdapterView.OnItemSelectedListener{
    private static final int UPDATE_LIST = 1;
    private Button send;
    private Button rec;
    private Button action;
    private Button pre;
    private Button next;
    private Button play_pause;
    private TextView bt_name;
    private TextView music_name;
    private IVDTUartBluetoothAidl ivdtUartBluetoothAidl = null;
    private ListView listView;
    private BtDevAdapter adapter;
    private List<EntityBluetoothDevice> devList;
    private Context context;
    private EntityBluetoothDevice curDev = null;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_LIST:
                    adapter.setList(devList);
                    break;
            };
        }
    };
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ivdtUartBluetoothAidl = IVDTUartBluetoothAidl.Stub.asInterface(service);
            try {
                List<EntityBluetoothDevice> list  =  ivdtUartBluetoothAidl.getPairBTList();
                if(list != null){
                    devList.clear();
                    devList.addAll(list);
                    handler.sendEmptyMessage(UPDATE_LIST);
                }
                Log.d("wgt","registerVDTUartCallback");
                ivdtUartBluetoothAidl.registerVDTUartCallback(mCallback);
                listView.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if(keyCode == KeyEvent.KEYCODE_0 && curDev != null){
                            try {
                                ivdtUartBluetoothAidl.deleteBTSendPairDevice(curDev);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                        return false;
                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("wgt","onServiceDisconnected");
            ivdtUartBluetoothAidl = null;
        }
    };
    private IVDTUartCallback mCallback = new IVDTUartCallback.Stub() {
        @Override
        public void onBluetoothSendModeStatusChange(EnumBTSendModeStatus enumBTSendModeStatus, EntityBluetoothDevice entityBluetoothDevice, List<EntityBluetoothDevice> list) throws RemoteException {
            Log.d("wgt","EnumBTSendModeStatus = " + enumBTSendModeStatus);
            switch (enumBTSendModeStatus){
                case STATUS_SEARCH_START:
                    if(list != null) {
                        devList.clear();
                        devList.addAll(list);
                        handler.sendEmptyMessage(UPDATE_LIST);
                    }
                    break;
                case STATUS_SEARCH_END:
                    if(list != null) {
                        devList.clear();
                        devList.addAll(list);
                        handler.sendEmptyMessage(UPDATE_LIST);
                    }
                    break;
                case STATUS_GET_NAME:
                    if(list != null) {
                        devList.clear();
                        devList.addAll(list);
                        Log.d("wgt",devList.get(0).getMAC() + devList.get(0).getName());
                        handler.sendEmptyMessage(UPDATE_LIST);

                    }
                    break;
                case STATUS_A2DP_DISCON:
                    if(list != null) {
                        devList.clear();
                        devList.addAll(list);
                        handler.sendEmptyMessage(UPDATE_LIST);
                    }
                    break;
                case STATUS_A2DP_CONNECTING:
                    if(list != null) {
                        devList.clear();
                        devList.addAll(list);
                        handler.sendEmptyMessage(UPDATE_LIST);
                    }
                    break;
            }
        }

        @Override
        public void onBluetoothSendDataChange(List<EntityBluetoothDevice> list) throws RemoteException {
            if(list != null) {
                devList.clear();
                devList.addAll(list);
                handler.sendEmptyMessage(UPDATE_LIST);
            }
        }

        @Override
        public void onBluetoothSendModeKey(EnumBluetoothKey enumBluetoothKey) throws RemoteException {

        }

        @Override
        public void onBluetoothRecModeStatusChange(EnumBTRecModeStatus enumBTRecModeStatus, EntityBluetoothDevice entityBluetoothDevice, List<EntityBluetoothDevice> list) throws RemoteException {

        }

        @Override
        public void onBluetoothRecMusicNameChange(String s) throws RemoteException {
            Log.d("wgt","onBluetoothRecMusicNameChange = " + s);
            music_name.setText(s);
        }

        @Override
        public void onBluetoothRecConnectedNameChange(String s) throws RemoteException {
            Log.d("wgt","onBluetoothRecConnectedNameChange = " + s);
            bt_name.setText(s);
        }

        @Override
        public void onGetBtVersion(EnumBluetoothMode enumBluetoothMode, String s) throws RemoteException {

        }

        @Override
        public void onGetBtVolume(EnumBluetoothMode enumBluetoothMode, int i) throws RemoteException {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        send = (Button)findViewById(R.id.test_send);
        send.setOnClickListener(this);
        rec = (Button)findViewById(R.id.test_rec);
        rec.setOnClickListener(this);
        action = (Button)findViewById(R.id.test_action);
        action.setOnClickListener(this);
        pre = (Button)findViewById(R.id.test_pre);
        pre.setOnClickListener(this);
        next = (Button)findViewById(R.id.test_next);
        next.setOnClickListener(this);
        play_pause = (Button)findViewById(R.id.test_play_pause);
        play_pause.setOnClickListener(this);

        bt_name = (TextView)findViewById(R.id.bt_name);
        music_name = (TextView)findViewById(R.id.music_name);
        devList = new ArrayList<EntityBluetoothDevice>();
        devList.clear();
        listView = (ListView)findViewById(R.id.list_bt_dev);
        adapter = new BtDevAdapter(context,devList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        listView.setOnItemSelectedListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.test_send:
                if(ivdtUartBluetoothAidl != null){
                    try {
                        ivdtUartBluetoothAidl.setBluetoothMode(EnumBluetoothMode.SEND_MODE);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.test_rec:
                if(ivdtUartBluetoothAidl != null){
                    try {
                        ivdtUartBluetoothAidl.setBluetoothMode(EnumBluetoothMode.REC_MODE);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.test_action:
                if(ivdtUartBluetoothAidl != null){
                    try {
                        adapter.setList(ivdtUartBluetoothAidl.getPairBTList());
                        ivdtUartBluetoothAidl.startSearchBTSendMode();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.test_pre:
                if(ivdtUartBluetoothAidl != null){
                    try {
                        ivdtUartBluetoothAidl.sendBTRecModeKey(EnumBluetoothKey.KEY_PREV);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.test_next:
                if(ivdtUartBluetoothAidl != null){
                    try {
                        ivdtUartBluetoothAidl.sendBTRecModeKey(EnumBluetoothKey.KEY_NEXT);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.test_play_pause:
                if(ivdtUartBluetoothAidl != null){
                    try {
                        ivdtUartBluetoothAidl.sendBTRecModeKey(EnumBluetoothKey.KEY_PLAY_PAUSE);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
    public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);

        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);

        // Set the component to be explicit
        explicitIntent.setComponent(component);

        return explicitIntent;
    }

    @Override
    protected void onStart() {
        final Intent intent = new Intent();
        intent.setAction("android.cvte.vdt.action.UARTSERVICE");
        final Intent eintent = new Intent(createExplicitFromImplicitIntent(this,intent));
        bindService(eintent, conn,BIND_AUTO_CREATE);
        super.onStart();
    }

    @Override
    protected void onPause() {
        try {
            if(ivdtUartBluetoothAidl != null) {
                Log.d("wgt","unregisterVDTUartCallback");
                ivdtUartBluetoothAidl.unregisterVDTUartCallback(mCallback);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        unbindService(conn);
        super.onPause();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EntityBluetoothDevice dev = devList.get(position);
        try {
        switch (dev.getStatus())
            {
                case DEV_NOT_PAIR:
                case DEV_CONNECTING:
                case DEV_PAIR:
                    ivdtUartBluetoothAidl.connectBTSendDevice(dev);
                    break;
                case DEV_CONNECTED:
                    ivdtUartBluetoothAidl.disconnectBTSendDevice(dev);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Log.d("wgt","onItemSelected");
        curDev = devList.get(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        Log.d("wgt","onNothingSelected");
    }
}
